#!/bin/bash
SCRIPT_BASE_DIR=$( dirname "${BASH_SOURCE[0]}" )
source "${SCRIPT_BASE_DIR}/common/eb_utils.sh"
source "${SCRIPT_BASE_DIR}/common/fs_utils.sh"

comm_plugets=(araEmManifestGen AraComBindingGenerator AraComManifestGenerator araPmManifestGen araPhmManifestGen)

function usage() {
    echo "$( basename $0 ) [-a <top_dir> | -m <app_dir1> -m <app_dir2> ...] [-p <pluget1> -p <pluget2>] [-l]"
    echo "      为<top_dir>下的所有eb app目录或者指定的eb demo项目生成配置文件或者代码"
    echo "      参数说明:"
    echo "      -a <top_dir> 对<top_dir>下所有eb app进行操作"
    echo "      -m <app_dir> 仅对<app_dir>下所有指定app进行操作"
    echo "      -p <pluget> 仅运行指定的pluget,默认运行${comm_plugets[@]}"
    echo "      -l 列出所有pluget"
    exit 1
}


function run_plugets() {
    local d="${1}"
    dir_exists_or_die "$d"

    for act in "${plugets[@]}"
    do
        echo ara-cli RunPluget --path "${d}/plugets/${act}.pluget" --input "${d}" --output "${d}"
        ara-cli RunPluget --path "${d}/plugets/${act}.pluget" --input "${d}" --output "${d}"
        sleep 2
        echo "***********************************************************"
    done
}

function list_plugets() {
    allP=($( all_plugets ${apps[0]} ))
    for p in ${allP[@]}
    do
        echo $p
    done
}

apps=()
plugets=()
listPlugets=0

while getopts ":a:m:p:l" arg
do
    case $arg in
        a)
            apps=($( all_apps ${OPTARG} ))
            ;;
        m)
            apps[${#apps[@]}]="${OPTARG}"
            ;;
        p)
            plugets[${#plugets[@]}]="${OPTARG}"
            ;;
        l)
            listPlugets=1
            ;;
        *)
            usage
            ;;
    esac
done

if [ 0 -eq ${#apps[@]} ]
then
    usage
fi

# echo "${apps[@]}"
# exit 

if [ 1 -eq "${listPlugets}" ]
then
    list_plugets
    exit 0
fi

if [ 0 -eq ${#plugets[@]} ]
then
    plugets=( "${comm_plugets[@]}" )
fi

# echo "${plugets[@]}"
# echo "${#plugets[@]}"
# exit 

for app in "${apps[@]}"
do
    run_plugets "${app}"
done
